import type { RouteRecordRaw } from "vue-router";
import { createRouter, createWebHashHistory } from "vue-router";
import { useUserStore } from "../store/model/user";
import * as http from "@/request/http";
import type { App } from "vue";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login.vue"),
  },
  {
    path: "/",
    redirect:"/index"
  },
  // {
  //   path:"/ums",
  //   name:"ums",
  //   component: () => import("../views/home.vue"),
  //   children:[
  //     {path:"admin",component: () => import("../views/ums/admin.vue")},
  //     {path:"resource",component: () => import("../views/ums/resource.vue")}
  //   ]
  // }
  //   {
  //     path: "/err",
  //     name: "err",
  //     component: () => import("../components/Err.vue"),
  //   },
  //   {
  //     path: "/:pathMatch(.*)",
  //     redirect: "/err",
  //   },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach(async (to, from, next) => {
  // console.log(to,from);
  let token = localStorage.getItem("token");
  const userStore = useUserStore();
  // console.log(token,userStore.menus.length);
  if (token && userStore.menus.length == 0) {
    const adminData = await http.admin.infoHttp();
    if (adminData.code == 200) {
      userStore.updateMenus(adminData.data.menus);
      const menusRoutes = userStore.getMenusRoutes;
      userStore.username = adminData.data.username
      for (let k in menusRoutes) {
        // console.log("for in", menusRoutes[k]);
        // 一级
        let routesObj: RouteRecordRaw = {
          path: "/" + menusRoutes[k].name,
          name: menusRoutes[k].name,
          component: () => import("../views/home.vue"),
          children: [],
        };
        // 二级
        menusRoutes[k].children?.forEach((item) => {
          routesObj.children!.push({
            path: item.name,
            name: item.name,
            component: () =>
              import(`../views/${menusRoutes[k].name}/${item.name}.vue`),
          });
        });
        // 添加路由方法
        // console.log("路由对象", routesObj);
        router.addRoute(routesObj);
      }
      router.addRoute({
          path: "/",
          component: () => import("../views/home.vue"),
          children:[
            {
              path:"index",component: () => import("../views/index.vue")
            }]
      })
      return next(to.fullPath);
    } 
  } else if (!token && to.path !== "/login") {
    return next("/login");
  } else if (token && userStore.menus.length !== 0 && to.path == "/login") {
    ElMessage.warning("请先退出登录!");
    return next(from.fullPath);
  } else {
    return next();
  }
});

// export default router
export function initRouter(app: App<Element>) {
  app.use(router);
}
export default router